<?php

namespace StudyBuddy\Controllers;

use StudyBuddy\WebPage;
use StudyBuddy\Responder;
use StudyBuddy\Request;
use StudyBuddy\UserAuth;

/**
 * This class is responsible for
 * handling login process
 * when login is via a web form
 * where a user presents username and password
 *
 */
class Login extends WebPage
{

	/**
	 * ONLY non-loggedin users
	 * can access this page
	 *
	 * @var bool
	 */
	// protected $guestsOnly = true;

	/**
	 * REQUEST_METHOD
	 * MUST be POST for this page
	 *
	 * @var bool
	 */
	protected $bRequirePost = true;
	
	protected $permission = 'login';


	public function main(){
		
		/**
		 * Will not check for the valid 'form token'
		 * in this form because potential
		 * hacher has nothing to gain by
		 * exploiting CSRF of a login form because
		 * the user using this form is be definition
		 * 'not yet logged in', so there is really
		 * nothing to gain by tricking someonw to login
		 */
		$bRemember = (isset($this->oRequest['chkRemember']) ? (bool)$this->oRequest['chkRemember'] : false);
		d('$bRemember '.$bRemember.' $this->oRequest '.print_r($this->oRequest->getArrayCopy(), 1));

		try {
			$oCheckLogin = new UserAuth($this->oRegistry);
			$oUser = $oCheckLogin->validateLogin($this->oRequest['login'], $this->oRequest['pwd']);
			/**
			 * If user logged in that means he got the email
			 * with password,
			 * thus we confirmed email address
			 * and can activate user
			 */
//			$oUser->activate();
		} catch(\StudyBuddy\LoginException $e) {
			e('Login error: '.$e->getMessage().' in file: '.$e->getFile().' on line: '.$e->getLine());
			if (Request::isAjax()) {
				Responder::sendJSON(array('error' => $e->getMessage()));
			}
			
			$_SESSION['login_error'] = $e->getMessage();
			d('$_SESSION[login_error] '.$_SESSION['login_error']);
			
			Responder::redirectToPage();
		}

		d('oUser: '.gettype($oUser));

		$this->processLogin($oUser);
		$this->oRegistry->Dispatcher->post( $this, 'onUserLogin' );

		if($bRemember){
			\StudyBuddy\Cookie::sendLoginCookie($oUser->getUid(), $oUser['rs']);
		}

		Responder::redirectToPage();
	}

}
